<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\CreateGoodsRequest;
use App\Http\Requests\UpdateGoodsRequest;
use App\Models\Article;
use App\Models\Category;
use App\Models\Color;
use App\Models\Goods;
use App\Models\Label;
use App\Models\Role;
use App\Models\GoodsSlideshow;
use App\Repositories\CategoryRepository;
use App\Repositories\ConfigRepository;
use App\Repositories\GoodsRepository;
use App\Http\Controllers\AppBaseController;
use App\ZL\ORG\Excel\ExcelHelper;
use Illuminate\Http\Request;
use Flash;
use Illuminate\Support\Facades\DB;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;

class GoodsController extends AppBaseController
{
    /** @var  GoodsRepository */
    private $goodsRepository;
    private $config;
    private $cate;

    public function __construct(GoodsRepository $goodsRepo, ConfigRepository $configRepository, CategoryRepository $categoryRepository)
    {
        $this->goodsRepository = $goodsRepo;
        $this->config = $configRepository;
        $this->cate = $categoryRepository;
    }
/**/
    /**
     * Display a listing of the Goods.
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        $model = new Goods();
        $session = session();
        if($request->seesion_clear){
            $session->forget('search_page');
        }
        $seesion_search = $request->seesion_search;
        if($seesion_search){
            if(session('search_page'))
                $request->merge(['page'=>session('search_page')]);
            if(session('search_title'))
                $request->merge(['title'=>session('search_title')]);
            if(session('search_technology'))
                $request->merge(['technology'=>session('search_technology')]);
            if(session('search_texture'))
                $request->merge(['texture'=>session('search_texture')]);
            if(session('search_cate_id'))
                $request->merge(['cate_id'=>session('search_cate_id')]);
        }
        if($request->page){
            session(['search_page'=>$request->page]);
        }

        if($request->title){
            $model = $model->where('title',"like","%$request->title%")->orWhere('sn',"like","%$request->title%");

            session(['search_title'=>$request->title]);
        }

        if($request->technology){
            $model = $model->where('technology',"like","%$request->technology%");

            session(['search_technology'=>$request->technology]);
        }

        if($request->texture){
            $model = $model->where('texture',"like","%$request->texture%");

            session(['search_texture'=>$request->texture]);
        }

        if($request->cate_id){
            $cate_ids = Category::where('pid',$request->cate_id)->pluck('id')->toArray();
            $model = $model->whereIn('category_id', $cate_ids);

            session(['search_cate_id'=>$request->cate_id]);
        }

        $goods = $model->where('is_delete',0)->orderBy('sort',"asc")->paginate(20);

        return view('goods.index')
            ->with('goods', $goods)
            ->with('cates', Category::where('level',1)->get())
            ->with('request',$request->all())->with('request',array_merge($request->all()));
    }

    /**
     * Show the form for creating a new Goods.
     *
     * @return Response
     */
    public function create()
    {
        $cats = $this->cate->getLevelData();
        $articles = Article::orderBy('id','desc')->get();
        $goods = Goods::where('is_delete',0)->orderBy('sn','asc')->get();
        $colors = Color::orderBy('id','desc')->get();
        $labels = Label::orderBy('id','desc')->get();
        $roles = Role::orderBy('id','desc')->get();
        $configs = $this->config->getMapByGroup('options');
        $technology = explode(',', $configs['technology']);
        $texture = explode(',', $configs['texture']);
        return view('goods.create')->with([
            'cats'=>$cats,
            'articles'=>$articles,
            'goods_all'=>$goods,
            'colors'=>$colors,
            'configs'=>$configs,
            'labels'=>$labels,
            'roles'=>$roles,
            'texture'=>$texture,
            'technology'=>$technology,
        ]);
    }

    /**
     * Store a newly created Goods in storage.
     *
     * @param CreateGoodsRequest $request
     *
     * @return Response
     */
    public function store(CreateGoodsRequest $request)
    {
        $input = $request->all();

        $goods = $this->goodsRepository->create($input);
        $this->goodsRepository->saveData($goods,$request);
        Flash::success('Goods saved successfully.');

        return redirect(route('goods.index'));
    }

    /**
     * Display the specified Goods.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $goods = $this->goodsRepository->findWithoutFail($id);

        if (empty($goods)) {
            Flash::error('Goods not found');

            return redirect(route('goods.index'));
        }

        return view('goods.show')->with('goods', $goods);
    }

    /**
     * Show the form for editing the specified Goods.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        $goods = $this->goodsRepository->findWithoutFail($id);

        if (empty($goods)) {
            Flash::error('Goods not found');

            return redirect(route('goods.index'));
        }
        $cats = $this->cate->getLevelData();
        $articles = Article::orderBy('id','desc')->get();
        $goods_all = Goods::where('is_delete',0)->orderBy('sn','asc')->get();
        $colors = Color::orderBy('id','desc')->get();
        $labels = Label::orderBy('id','desc')->get();
        $roles = Role::orderBy('id','desc')->get();
        $configs = $this->config->getMapByGroup('options');
        $technology = explode(',', $configs['technology']);
        $texture = explode(',', $configs['texture']);
        return view('goods.edit')->with('goods', $goods)->with([
            'cats'=>$cats,
            'articles'=>$articles,
            'goods_all'=>$goods_all,
            'colors'=>$colors,
            'configs'=>$configs,
            'labels'=>$labels,
            'roles'=>$roles,
            'texture'=>$texture,
            'technology'=>$technology,
        ]);
    }

    /**
     * Update the specified Goods in storage.
     *
     * @param  int              $id
     * @param UpdateGoodsRequest $request
     *
     * @return Response
     */
    public function update($id, UpdateGoodsRequest $request)
    {
        $goods = $this->goodsRepository->findWithoutFail($id);

        if (empty($goods)) {
            Flash::error('Goods not found');

            return redirect(route('goods.index'));
        }

        $goods = $this->goodsRepository->update($request->all(), $id);
        $this->goodsRepository->saveData($goods,$request);
        Flash::success('Goods updated successfully.');

        return redirect(route('goods.index',['seesion_search'=>1]));
    }

    /**
     * Remove the specified Goods from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        $goods = $this->goodsRepository->findWithoutFail($id);

        if (empty($goods)) {
            Flash::error('Goods not found');

            return redirect(route('goods.index'));
        }
        $goods->is_delete = 1;
        $goods->save();
//        $this->goodsRepository->delete($id);

        Flash::success('Goods deleted successfully.');

        return redirect(route('goods.index',['seesion_search'=>1]));
    }
    /**
    *
    */
    public function delpic(){
      $picid = $_POST['picid'];
      GoodsSlideshow::where('id',$picid)->delete();
      $rs['code'] = '200';
      $rs['msg'] = '删除成功';
      return Response::json($rs);
    }
    public function postExcel(Request $request)
    {
        $file = $request->file('file');
        $excel = new ExcelHelper();
        $array = ExcelHelper::getArr($file->getRealPath(),0,1);
        dump($array);
        foreach ($array as $v) {
            $_data = [];
            $_data['sn'] = $v['货号'];
            if(!$_data['sn'])
                continue;
            $_data['title'] = $v['名称'];
            $_data['abstract'] = $v['简介'];
            $_data['length'] = $v['长'];
            $_data['wide'] = $v['宽'];
            $_data['gram_weight'] = $v['克重'];
            $_data['price'] = $v['价格'];
            $_data['texture'] = $v['材质(用,隔开)'];
            $_data['technology'] = $v['工艺(用,隔开)'];
            $_data['labels'] = $v['标签(用,隔开)'];
            $_data['sort'] = $v['排序(越小越前)'];
            $_data['categorie'] = $v['分类'];
            $_goods = Goods::create($_data);
            if(!is_float($_data['price']))
                $_data['price'] = 0;
            $_labels = explode(',', $_data['labels']);
            if($_labels){
                $_label_ids = [];
                foreach ($_labels as $_label) {
                    $has = Label::where('title',$_label)->first();
                    if($has)
                        $_label_ids[] = $has->id;
                }
                $_goods->labels()->sync($has);
            }
            if($_data['categorie']){
                $_cate_arr = explode('-',$_data['categorie']);
                $p = Category::where('title',$_cate_arr[0])->first();
                if($p){
                    $c = Category::where('pid',$p->id)->where('title',$_cate_arr[1])->first();
                    if($c){
                        $_goods->category_id = $c->id;
                        $_goods->save();
                    }
                }
            }
        }
    }
}
